package org.pjx.spm.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import io.swagger.annotations.ApiOperation;
import org.pjx.spm.pojo.Employee;
import org.pjx.spm.pojo.User;
import org.pjx.spm.pojo.VerifyCode;
import org.pjx.spm.pojo.employee_request;
import org.pjx.spm.service.Department_empServiceImpl;
import org.pjx.spm.service.EmployeeServiceImpl;
import org.pjx.spm.service.UserServiceImpl;
import org.pjx.spm.util.config.VerifyCodeGeneral;
import org.pjx.spm.util.interfacespecfiaction.RespBean;
import org.pjx.spm.util.kaptcha.VerifyCodeKaptchaConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.rmi.runtime.Log;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author Glow
 * @Date 2022-01-29 21:19:58
 * @Description 登录注册模块
 * @Version 1.0
 */
@CrossOrigin
@Controller
public class loginController {

    private final static Logger logger = LoggerFactory.getLogger(loginController.class);
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RedisTemplate<String, Object> redisTemplates;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private EmployeeServiceImpl employeeService;
    @Autowired
    private Department_empServiceImpl department_empService;
    /**
     * 验证码controller
     * @param httpServletRequest
     * @param httpServletResponse
     */
    @ApiOperation(value = "验证码")
    @GetMapping("/verifyCode")
    public void loginVerifyCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)  {
        httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
//        logger.info("验证码路径"+(String)httpServletRequest.getContextPath());
        VerifyCodeGeneral verifyCodeGeneral = new VerifyCodeKaptchaConfig();
        try {
            //设置验证码图片的长宽、及其随机验证码结果
            VerifyCode verifyCode = verifyCodeGeneral.generate(80,30);
            String code = verifyCode.getCode();
            redisTemplate.opsForValue().set("verifyCode",code);
            redisTemplate.expire("verifyCode",90, TimeUnit.SECONDS);

            logger.info("验证码:"+code);
//            //酱verifyCode绑定session
//            httpServletRequest.getSession().setAttribute("verifyCode",verifyCode);
//            //为verifyCode设置失效时间
//            httpServletRequest.getSession().setMaxInactiveInterval(1000*60);
            //设置header
            httpServletResponse.setHeader("Pragma","no-cache");
            //设置响应头
            httpServletResponse.setHeader("Cache-Control","no-cache");
            //在服务端禁用缓冲加载
            httpServletResponse.setDateHeader("Expire",0);
            //设置响应内容类型
            httpServletResponse.setContentType("image/jpeg");
            httpServletResponse.getOutputStream().write(verifyCode.getImgBytes());
            httpServletResponse.getOutputStream().flush();
        }catch (IOException e)
        {
            logger.info("",e);
        }



    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户登录验证")
    public RespBean checkuserAndPwdAndVerify(@RequestBody Map<String,String>map, HttpServletResponse httpServletResponse, HttpServletRequest request, HttpSession httpSession)
    {   User user = new User();
        user.setUserId(map.get("userId"));
        user.setPassword(map.get("password"));
        logger.info("入参："+user.toString());
        String isTrueKey = redisTemplate.opsForValue().get("verifyCode");
        logger.info(isTrueKey);
        if (isTrueKey == null||!isTrueKey.equals(map.get("verify")) )
        {
            logger.info("验证码失效或错误!");
            return RespBean.error("FalseVerify");
        }
        if (user == null)
        {
            logger.info("用户账号或密码不能为空！");
            return RespBean.error("NoaccountOrPassword");
        }
        int res = userService.accountIsTrue(user.getUserId(),user.getPassword());
        if(res == 1)
        {
            logger.info("用户登录成功！欢迎用户"+user.getUserId()+"!");
//            httpSession.setAttribute("userId",user.getUserId());
//            logger.info("userid：session："+(String)httpSession.getAttribute("userId"));
            redisTemplate.delete("verifyCode");
            //2022-04-16
            //生成token，验证登录失效时间
            String str="abcdefghijklmnopqrstuvwxyz1234567890";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<15;i++) {
                int number = random.nextInt(36);            //可随机产生字符的数量
                sb.append(str.charAt(number));
            }
            String token = sb.toString();
            userService.updatetokenByuserId(token,user.getUserId());
            //存储用户信息到redis缓存
            User users = new User();
            users = userService.selectUserById(user.getUserId());
            logger.info("入参 users："+users.toString());
            redisTemplates.opsForValue().set("USER:"+user.getUserId(),users);
            redisTemplates.expire("USER:"+user.getUserId(),3600, TimeUnit.SECONDS);
            User checkuser = new User();
            checkuser = (User)redisTemplates.opsForValue().get("USER:"+user.getUserId());
            logger.info("身份信息："+checkuser.toString());
            Employee emp = new Employee();
            emp = employeeService.getEmployeeById(map.get("userId"));
            if(emp == null)
            {

                employeeService.InsertInitEmp(
                        users.getUserId(),
                        users.getUsername(),
                        users.getRole(),
                        users.getEmail());
                department_empService.InsertInitDepEmp(
                        users.getUserId(),
                        users.getUsername(),
                        users.getRole());
                return RespBean.error("okbutnotemployee");
            }
            logger.info("员工信息放redis前："+emp.toString());
            redisTemplates.opsForValue().set("EMPLOYEER:"+emp.getUserId(),emp);
            redisTemplates.expire("EMPLOYEER:"+emp.getUserId(),3600,TimeUnit.SECONDS);
            Employee emps = new Employee();
            emps =(Employee) redisTemplates.opsForValue().get("EMPLOYEER:"+emp.getUserId());
            logger.info("员工信息放redis后："+emps.toString());
            return RespBean.ok("successlogin");
        }
        else {
            logger.info("用户名或密码错误");
            return RespBean.error("failaccorpassword");
        }

    }

    @RequestMapping(value = "/getUser",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("获取用户信息")
    public User testsession(@RequestBody Map<String,String>map)
    {
        User checkuser = new User();
        logger.info("获取的ID:"+map.get("userId"));
        checkuser = (User)redisTemplates.opsForValue().get("USER:"+map.get("userId"));
        logger.info("获取身份信息："+checkuser.toString());
        return checkuser;
    }

    /**
     * 修改密码
     * @param userdatas
     * @param httpServletResponse
     * @return
     */
    @ApiOperation("修改密码")
    @ResponseBody
    @RequestMapping(value ="/changepassword",method = RequestMethod.POST)
    public RespBean changepassword( @RequestBody  Map<String,String>userdatas,HttpServletResponse httpServletResponse)
    {


        logger.info("接收的数据为："+userdatas.toString());
        String userid =userdatas.get("userId");
        String oldpassword = userdatas.get("oldPassword");
        String password = userdatas.get("newPassword");
     int res =  userService.accountIsTrue(userid,oldpassword);
     if(res == 1)
     {
         User user = new User();
         user.setUserId(userid);
         user.setPassword(password);
      int reschange =  userService.changePassword(user);
      if (reschange == 1)
      {logger.info("提示信息，用户密码更改成功~ 为："+userdatas.get("newPassword"));
          return RespBean.ok("success");
      }
     }
     else {
         logger.info("提示信息，用户旧版密码错误");
         return RespBean.error("falseoldpassword");
     }
        logger.info("请求超时哦~");
     return RespBean.error("missingfail");
    }

    /**
     * 请求密码
     * @param map
     * @param httpServletResponse
     * @return
     */
    @ApiOperation("请求密码")
    @ResponseBody
    @RequestMapping(value = "/RequestFindPassword",method = RequestMethod.POST)
    public RespBean RequestFindPassword(@RequestBody Map<String,String>map,HttpServletResponse httpServletResponse)
    {
        logger.info("查询该用户是否存在ing："+map.get("userId"));
        int res = userService.userIsExistById(map.get("userId"));
        if(res == 1)
        {
            int employeerequestexist = userService.userrequestIsExistById(map.get("userId"));
            if(employeerequestexist == 1)
            {
                logger.info("已有相同的请求，请重试");
                return RespBean.error("samerequest");
            }
            employee_request employeeRequest = new employee_request();
            employeeRequest.setUserId(map.get("userId"));
            employeeRequest.setCheckcode(map.get("checkcode"));
            employeeRequest.setIsavailable(1);
            employeeRequest.setRequestoftype("resetpassword");
            employeeRequest.setRequestcode("");
            int createrequest =userService.requestsetpassword(employeeRequest);
            if (createrequest == 1)
            {
                logger.info("用户："+map.get("userId")+"重设密码请求发送成功，请等待管理员通知!请求码为："+map.get("checkcode"));
                return RespBean.ok("success");
            }

        }
         logger.info("no user");
        return RespBean.error("nouser");
    }

    /**
     * 删除因记得密码的操作后的忘记密码请求
     * @param userdata
     * @return
     */
    @ApiOperation("删除因记得密码的操作后的忘记密码请求")
    @ResponseBody
    @RequestMapping(value = "/deletepasswordrequest",method = RequestMethod.POST)
    public RespBean deletepasswordrequest(@RequestBody Map<String,String>userdata)
    {
      int res =  userService.deletepasswordrequestById(userdata.get("userId"));
      logger.info(userdata.get("userId"));
        if(res == 1)
        {
            logger.info("删除密码申请记录成功");
            return RespBean.ok("success");
        }
        logger.info("无此记录可删除或者服务超时");
        return RespBean.error("faildelete");
    }
    @ApiOperation("查询密码是否被重置")
    @ResponseBody
    @RequestMapping(value = "/FindPassword",method = RequestMethod.POST)
    public RespBean searchpassword(@RequestBody Map<String,String> map,HttpServletResponse response)
    {
        int employeerequestexist = userService.userrequestAndCheckcodeIsExistById(map.get("userId"),map.get("checkcode"));
        if(employeerequestexist == 0)
        {
            logger.info("密码请求未审核通过或提取码错误！");
            return RespBean.error("noverify");
        }

            return RespBean.ok("success");
        }
    @ApiOperation("给用户返回初始密码")
    @ResponseBody
    @RequestMapping(value = "/getnewPassword",method = RequestMethod.POST)
    public User getnewPassword(@RequestBody User user,HttpServletRequest  request,HttpServletResponse response)
    {
        int res = userService.getnewpassword(user);
        if (res == 1) {
            int delres = userService.deletepasswordrequestById(user.getUserId());
            if (delres == 1) {
                String password = userService.getoriginpasswordById(user.getUserId());
                logger.info("重置密码成功！你的初始密码为：" + password);
               user.setPassword(password);
            }
        }
        logger.info(user.toString());
        return user;
    }
    @ResponseBody
    @RequestMapping(value = "/testjson",method = RequestMethod.GET)
    public User getjson()
    {
        User user = new User();
        user.setPassword("11");user.setUserId("12");
        return  user;
    }
    @ApiOperation("根据userId修改邮箱和姓名和权限")
    @ResponseBody
    @RequestMapping(value = "/updateusernameAndemailAndroleById",method = RequestMethod.POST)
    private RespBean updateusernameAndemailAndroleById(@RequestBody User user)
    {
        logger.info("updateusernameAndemailAndroleById："+user.getEmail()+":"+user.getUsername()+":"+user.getRole());
        int res = userService.updateusernameAndemailAndroleById(user);
        if (res == 1)
        {
            return RespBean.ok("修改成功惹");
        }
        else {
            return RespBean.error("修改邮箱、姓名、权限失败惹");
        }

    }
    @ApiOperation("根据userId修改邮箱和姓名")
    @ResponseBody
    @RequestMapping(value = "/updateusernameAndemailById",method = RequestMethod.POST)
    private RespBean updateusernameAndemailById(@RequestBody User user)
    {
        logger.info("updateusernameAndemailById："+user.getEmail()+":"+user.getUsername());
        int res = userService.updateusernameAndemailById(user);
        if (res == 1)
        {
            return RespBean.ok("修改成功惹");
        }
        else {
            return RespBean.error("修改邮箱和id失败惹");
        }

    }
    @ApiOperation("根据userId查找邮箱和姓名和权限")
    @ResponseBody
    @RequestMapping(value = "/getUsernameAndEmailAndroleById",method = RequestMethod.POST)
    private Map<String,Object> getUsernameAndEmailAndroleById(@RequestBody Map<String,String>map)
    {
        String userId = map.get("userId");
        logger.info("获取user的ID:"+userId);
        Map<String,Object> maps = userService.getUsernameAndEmailAndroleById(userId);
        logger.info("获取user的邮箱和姓名和权限:"+maps);
        return maps;
    }

    @ApiOperation("token登录判断")
    @ResponseBody
    @RequestMapping(value = "/checktokenAndRoleAndTime",method = RequestMethod.POST)
    private RespBean checktokenAndRoleAndTime(@RequestBody Map<String,String>map) {
        System.out.println(map.get("userId"));
      User user =  userService.selectUserById(map.get("userId"));
      if((User)redisTemplates.opsForValue().get("USER:"+user.getUserId())==null)
      {
          return RespBean.ok("outlogin");
      }
      User users = (User)redisTemplates.opsForValue().get("USER:"+user.getUserId());
        if(users.getToken().equals(user.getToken()))
        {
            return RespBean.ok("1");
        }
        return RespBean.ok("outlogin");

    }

}
